package com.myapp.msg.define;

import java.io.File;

import org.apache.log4j.Logger;

import com.myapp.data.global.Instances;
import com.myapp.msg.ann.MsgDefine;

public class MsgManager {

	// 日志
	private Logger log = Logger.getLogger(MsgManager.class);

	private static MsgManager msgManager = null;

	public static MsgManager getInstance() {
		if (msgManager == null) {
			msgManager = new MsgManager();
		}
		return msgManager;
	}

	/**
	 * 加载消息配置
	 */
	public void loadMsgConfig() {
		// 清空容器
		Instances.getMsgContainer().clear();
		// 重新加载
		File msgPath = new File(Instances.getAppConfigBean().getCurrentPath()
				+ Instances.getAppConfigBean().getMsgPath());
		this.initPath(msgPath);
	}

	private void initPath(File path) {
		if (path.isDirectory()) {
			File[] files = path.listFiles();
			for (File file : files) {
				this.initPath(file);
			}
		} else {
			this.initFile(path);
		}
	}

	@SuppressWarnings("unchecked")
	private void initFile(File file) {
		String path = file.getAbsolutePath();
		int start = path.indexOf("com");
		if (start != -1) {
			String className = path.substring(start);
			if (className.endsWith(".class")) {
				className = className.substring(0, className.length() - 6);
			}
			className = className.replaceAll("/", ".");
			className = className.replaceAll("\\\\", ".");
			try {
				@SuppressWarnings("rawtypes")
				Class clazz = Class.forName(className);
				if (clazz.isAnnotationPresent(MsgDefine.class)) {
					MsgDefine msgDefine = (MsgDefine) clazz
							.getAnnotation(MsgDefine.class);
					// 初始化配置bean
					MsgConfigBean msgConfigBean = new MsgConfigBean();
					msgConfigBean.setId(msgDefine.id());
					msgConfigBean.setName(msgDefine.name());
					msgConfigBean.setCanUse(msgDefine.canUse());
					msgConfigBean.setLogicalClass(msgDefine.logicalClass());
					msgConfigBean.setMsgClass(clazz);
					msgConfigBean.setPermission(msgDefine.permission());
					// 保存配置
					Instances.getMsgContainer().addMsgConfig(msgConfigBean);
				}
			} catch (ClassNotFoundException e) {
				log.error(String.format("Class[%s] not found", path), e);
				System.exit(1);
			}
		}
	}
}
